<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket_TEST</title>
</head>
<body>
<textarea class="log" style="width: 100%; height: 500px;">
=======websocket======
</textarea>
<input type="button" value="连接" onClick="link()">
<input type="button" value="断开" onClick="dis()">
<input type="text" id="text">
<input type="button" value="发送" onClick="send()">
<script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
    socket = null;//默认为空
    function link() {
        var url = 'ws://localhost:8000';
        socket = new WebSocket(url);
        socket.onopen = function () {
            log('连接成功')
        }
        socket.onmessage = function (msg) {
            log('获得消息:' + msg.data);
            console.log(msg);
        }
        socket.onclose = function () {
            log('断开连接')
        }
    }

    function dis() {
        socket.close();
        socket = null;
    }

    function log(var1) {
        $('.log').append(var1 + "\r\n");
    }

    function send() {
        let text = $('#text').val();
        if(socket==null) {
            log('请连接后再试！');
        } else if (text == '') {
            log('信息为空！');
        } else {
            socket.send(text);
        }
    }

    $(document).keyup(function (event) {
        if (event.keyCode == 13) send();
    });
</script>
</body>
</html>